package org.jeecg.modules.smoke.util;

import org.springframework.stereotype.Service;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

@Service
public class SocketClientService {

    public void sendDataToServer(String host, int port, String hexData) {

        try {
            // 创建Socket连接
            Socket socket = new Socket(host, port);
            // 获取输出流
            DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());

            // 将16进制字符串转换为字节数组
            byte[] bytes = hexStringToByteArray(hexData);

            // 发送数据
            outputStream.write(bytes);

            // 关闭流和Socket
            outputStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 辅助方法：将16进制字符串转换为字节数组
    private byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }
}
